package org.jeecgframework.web.service.impl;

import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.service.*;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.system.service.UserService;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.Serializable;

@Service("cbsServiceReportService")
@Transactional
public class CbsServiceReportServiceImpl extends CommonServiceImpl implements CbsServiceReportServiceI {

    @Autowired
    ZyCommonService zyCommonService;
    @Autowired
    private UserService userService;
    @Autowired
    SystemService systemService;
    @Autowired
    private CbsInspectionEvaluateServiceI cbsInspectionEvaluateService;
    @Autowired
    private CbsServiceLogServiceI cbsServiceLogServiceI;
    @Autowired
    private WxCommonService wxCommonService;

    public <T> void delete(T entity) {
        super.delete(entity);
        //执行删除操作配置的sql增强
        this.doDelSql((CbsServiceReportEntity) entity);
    }

    public <T> Serializable save(T entity) {
        Serializable t = super.save(entity);
        //执行新增操作配置的sql增强
        this.doAddSql((CbsServiceReportEntity) entity);
        return t;
    }

    public <T> void saveOrUpdate(T entity) {
        super.saveOrUpdate(entity);
        //执行更新操作配置的sql增强
        this.doUpdateSql((CbsServiceReportEntity) entity);
    }

    /**
     * 默认按钮-sql增强-新增操作
     *
     * @param
     * @return
     */
    public boolean doAddSql(CbsServiceReportEntity t) {
        return true;
    }

    /**
     * 默认按钮-sql增强-更新操作
     *
     * @param
     * @return
     */
    public boolean doUpdateSql(CbsServiceReportEntity t) {
        return true;
    }

    /**
     * 默认按钮-sql增强-删除操作
     *
     * @param
     * @return
     */
    public boolean doDelSql(CbsServiceReportEntity t) {
        return true;
    }

    @Override
    public Map<String, Object> getCharacter(String serviceId) {
        Map<String, Object> map = new HashMap<>();
// 		boolean b = false;
        if (StringUtil.isNotEmpty(serviceId)) {
            CbsServiceEntity cbsServiceEntity = systemService.getEntity(CbsServiceEntity.class, serviceId);
            //判断该单是否有返件
            List<CbsReturnEquipmentEntity> returnEquipmentEntityList = systemService.findHql("from CbsReturnEquipmentEntity where crCode = '" + cbsServiceEntity.getCode() + "'");
            if (returnEquipmentEntityList != null && returnEquipmentEntityList.size() > 0) {
                TSUser tsUser = ResourceUtil.getSessionUserName();
//				String roleType = null;
                List<Map<String, Object>> roleList = systemService.findForJdbc("SELECT * FROM t_s_role r LEFT JOIN t_s_role_user u ON r.id = u.roleid where u.userid = '" + tsUser.getId() + "';");
                if (StringUtil.isNotEmpty(roleList)) {
                    if (roleList.size() > 0) {
                        String num = (String) roleList.get(0).get("rolecode");
                        if ("thirdPartyEngineer".equals(num)) {
                            map.put("role", "EG");
//							b = true;
                        } else if ("areaEngineer".equals(num)) {
                            map.put("role", "AEG");
//							b = true;
                        } else if ("barcoCSE".equals(num)) {
                            map.put("role", "barcoCSE");
//							b = true;
                        } else if ("barcoHelpdesk".equals(num)) {
                            map.put("role", "HD");
                        }
                    }
                }
            }
        } else {

            return map;

        }
        return map;
    }

    /**
     * 替换sql中的变量
     *
     * @param sql
     * @return
     */
    public String replaceVal(String sql, CbsServiceReportEntity t) {
        sql = sql.replace("#{id}", String.valueOf(t.getId()));
        sql = sql.replace("#{report_category}", String.valueOf(t.getReportCategory()));
        sql = sql.replace("#{service_id}", String.valueOf(t.getServiceId()));
        sql = sql.replace("#{scene_total}", String.valueOf(t.getSceneTotal()));
        sql = sql.replace("#{finish_file}", String.valueOf(t.getFinishFile()));
        sql = sql.replace("#{repair_front_file}", String.valueOf(t.getRepairFrontFile()));
        sql = sql.replace("#{repair_after_file}", String.valueOf(t.getRepairAfterFile()));
        sql = sql.replace("#{delay_file}", String.valueOf(t.getDelayFile()));
        sql = sql.replace("#{rectification_file}", String.valueOf(t.getRectificationFile()));
        sql = sql.replace("#{sn}", String.valueOf(t.getSn()));
        sql = sql.replace("#{equipment_type}", String.valueOf(t.getEquipmentType()));
        sql = sql.replace("#{equipment_run_time}", String.valueOf(t.getEquipmentRunTime()));
        sql = sql.replace("#{jg_reform}", String.valueOf(t.getJgReform()));
        sql = sql.replace("#{lwzk}", String.valueOf(t.getLwzk()));
        sql = sql.replace("#{pfsz}", String.valueOf(t.getPfsz()));
        sql = sql.replace("#{wd}", String.valueOf(t.getWd()));
        sql = sql.replace("#{dy}", String.valueOf(t.getDy()));
        sql = sql.replace("#{sd}", String.valueOf(t.getSd()));
        sql = sql.replace("#{lddy}", String.valueOf(t.getLddy()));
        sql = sql.replace("#{gypp}", String.valueOf(t.getGypp()));
        sql = sql.replace("#{gyxh}", String.valueOf(t.getGyxh()));
        sql = sql.replace("#{gy_run_time}", String.valueOf(t.getGyRunTime()));
        sql = sql.replace("#{ddcs}", String.valueOf(t.getDdcs()));
        sql = sql.replace("#{server_type}", String.valueOf(t.getServerType()));
        sql = sql.replace("#{server_sn}", String.valueOf(t.getServerSn()));
        sql = sql.replace("#{server_soft_ver}", String.valueOf(t.getServerSoftVer()));
        sql = sql.replace("#{server_3d_type}", String.valueOf(t.getServer3dType()));
        sql = sql.replace("#{server_3d_sn}", String.valueOf(t.getServer3dSn()));
        sql = sql.replace("#{soft_v1}", String.valueOf(t.getSoftV1()));
        sql = sql.replace("#{repair_front1}", String.valueOf(t.getRepairFront1()));
        sql = sql.replace("#{repair_after1}", String.valueOf(t.getRepairAfter1()));
        sql = sql.replace("#{soft_v2}", String.valueOf(t.getSoftV2()));
        sql = sql.replace("#{repair_front2}", String.valueOf(t.getRepairFront2()));
        sql = sql.replace("#{repair_after2}", String.valueOf(t.getRepairAfter2()));
        sql = sql.replace("#{soft_v3}", String.valueOf(t.getSoftV3()));
        sql = sql.replace("#{repair_front3}", String.valueOf(t.getRepairFront3()));
        sql = sql.replace("#{repair_after3}", String.valueOf(t.getRepairAfter3()));
        sql = sql.replace("#{soft_v4}", String.valueOf(t.getSoftV4()));
        sql = sql.replace("#{repair_front4}", String.valueOf(t.getRepairFront4()));
        sql = sql.replace("#{repair_after4}", String.valueOf(t.getRepairAfter4()));
        sql = sql.replace("#{gcq}", String.valueOf(t.getGcq()));
        sql = sql.replace("#{gzxx}", String.valueOf(t.getGzxx()));
        sql = sql.replace("#{cljg}", String.valueOf(t.getCljg()));
        sql = sql.replace("#{memo}", String.valueOf(t.getMemo()));
        sql = sql.replace("#{status}", String.valueOf(t.getStatus()));
        sql = sql.replace("#{create_name}", String.valueOf(t.getCreateName()));
        sql = sql.replace("#{create_by}", String.valueOf(t.getCreateBy()));
        sql = sql.replace("#{create_date}", String.valueOf(t.getCreateDate()));
        sql = sql.replace("#{update_name}", String.valueOf(t.getUpdateName()));
        sql = sql.replace("#{update_by}", String.valueOf(t.getUpdateBy()));
        sql = sql.replace("#{update_date}", String.valueOf(t.getUpdateDate()));
        sql = sql.replace("#{UUID}", UUID.randomUUID().toString());
        return sql;
    }

    //工程师PC端提交完工且需HD关单 发送邮件提醒
    @Override
    public void sendEmailToHD(String serviceId) {
        //获取登录的用户信息
        TSUser user = ResourceUtil.getSessionUserName();
        //用户的角色集合
        List<String> roleList = new ArrayList<>();
        List<TSRoleUser> tsRoleUserList = systemService.findHql("from TSRoleUser where TSUser.id='" + user.getId() + "'");
        for (TSRoleUser tsRoleUser : tsRoleUserList) {
            String role = tsRoleUser.getTSRole().getRoleCode();
            roleList.add(role);
        }
        //判断登录用户身份
        if (roleList.contains("thirdPartyEngineer") || roleList.contains("areaEngineer")) {
            //获取服务商信息
            List<String> shortnameList = systemService.findListbySql("select d.shortname from t_s_depart d left join cbs_service cbs on d.org_code = cbs.service_provider_code where cbs.id='" + serviceId + "'");
            String shortname = "";
            if (shortnameList.size() != 0) {
                shortname = shortnameList.get(0);
            }
            CbsServiceEntity cbsService = systemService.getEntity(CbsServiceEntity.class, serviceId);
            List<ZyEngineerEntity> zyEngineerHql = systemService.findHql("from ZyEngineerEntity where id = '" + cbsService.getEngineer() + "'");
            String emailTital = "服务单手动关单通知：<" + shortname + ">-<" + cbsService.getLevel() + ">-<" + cbsService.getServiceType1().getName() + "," + cbsService.getServiceType2().getName() + ">-<" + cbsService.getCode() + ">-<" + cbsService.getZyCinemaName() + ">-" + getDateStr(new Date());
            String emailContent = "服务单号<" + cbsService.getCode() + ">已完工，需要您审核后手动进行关单操作。如有疑问请联系现场工程师：<" + zyEngineerHql.get(0).getName() + "><" + zyEngineerHql.get(0).getCellphone() + ">\n" +
                    "具体内容请查看http://cbs.cfg-barco.com或登陆巴可客服App。\n" +
                    "【中影巴可客服部】\n" +
                    "* 该邮件请勿回复";
            //5月7号添加查询条件，正常状态下的用户
            List<String> listbySql = systemService.findListbySql("select email from t_s_user u LEFT JOIN t_s_role_user ru ON u.id=ru.userid LEFT JOIN t_s_role r ON ru.roleid=r.id LEFT JOIN t_s_base_user b on b.id = u.id where b.`status` = '" + Globals.User_Normal + "' and r.rolecode='" + StaticValue.CBS_HD_ROLE_CODE + "'");
            for (int i = 0; i < listbySql.size(); i++) {
                SendMailUtil.sendeMail(listbySql.get(i), emailTital, emailContent, systemService);
            }
        }

    }

    @Override
    public AjaxJson saveReport(HttpServletRequest request, CbsEngineSceneCheckReportEntity cbsEngineSceneCheckReport) {
        AjaxJson j = new AjaxJson();
        String msg = "提交引擎翻新现场检测完工单成功！";
        boolean flag = true;
        String type = request.getParameter("type"); //完工单类型

        //是否为补填完工单
        Boolean editReport = Boolean.valueOf(oConvertUtils.getString(request.getParameter("editReport")));
        try {
            String serviceId = cbsEngineSceneCheckReport.getServiceId(); //服务单id
            if (StringUtil.isNotEmpty(serviceId)) {
                //查询是否状态是否未完工
                //如果是补填完工单 或者 状态不是7
                List<Map<String, Object>> speedStatus = systemService.findForJdbc("select speed_status from cbs_service where id='" + serviceId + "'");
                if (editReport || (speedStatus.size() > 0 && !"7".equals(speedStatus.get(0).get("speed_status").toString()))) {
                    //status 暂存是0 ，提交是1，为了防止重复提交，先更新服务单状态
                    //如果不是补填完工单则更新服务单状态（防止影响原服务单状态）
                    if (!editReport && "1".equals(cbsEngineSceneCheckReport.getStatus())) {
                        systemService.updateBySqlString("update cbs_service set speed_status='" + StaticValue.fwywc + "' where id='" + serviceId + "'");
                    }

                    List<String> typeList = systemService.findListbySql("select type from zy_es_item where item='" + cbsEngineSceneCheckReport.getEquipmentType() + "'");
                    if (typeList.size() != 0) {
                        ZyEquipmentTypeEntity zyEquipmentType = systemService.getEntity(ZyEquipmentTypeEntity.class, typeList.get(0));
                        cbsEngineSceneCheckReport.setTypeId(zyEquipmentType);
                    }
                    cbsEngineSceneCheckReport.setReportCategory("4");
                    if ("".equals(cbsEngineSceneCheckReport.getId())) {
                        cbsEngineSceneCheckReport.setId(null);
                    }

                    if (cbsEngineSceneCheckReport.getId() != null && !"".equals(cbsEngineSceneCheckReport.getId())) {
                        CbsEngineSceneCheckReportEntity t = systemService.get(CbsEngineSceneCheckReportEntity.class, cbsEngineSceneCheckReport.getId());
                        MyBeanUtils.copyBeanNotNull2Bean(cbsEngineSceneCheckReport, t);
                        systemService.saveOrUpdate(t);
                    } else {
                        systemService.saveOrUpdate(cbsEngineSceneCheckReport);
                    }

                    //提交后对服务单的操作
                    if ("1".equals(cbsEngineSceneCheckReport.getStatus())) {
                        //非 补填完工单时
                        if(!editReport){
                            //判断服务单完工时，是否需要自动创建回访
                            cbsInspectionEvaluateService.assessService(serviceId);
                            List<CbsEngineSceneCheckReportEntity> hql = systemService.findHql("from CbsEngineSceneCheckReportEntity where serviceId='" + serviceId + "'");
                            systemService.updateBySqlString("update cbs_service set report_type='3' ,report_id='" + hql.get(0).getId() + "' where id='" + serviceId + "'");
                            //关单时间
                            //获取系统当前时间
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String s = sdf.format(new Date());
                            List<Integer> listbySql = systemService.findListbySql("select hd_close from cbs_service where id='" + serviceId + "'");
                            if (StringUtil.isNotEmpty(type) && type.equals("2")) {
                                systemService.updateBySqlString("update cbs_service set close_time ='" + s + "',status='4',speed_status='7' where id='" + serviceId + "'");
                            } else {
                                if (listbySql.size() != 0 && listbySql.get(0) != null && !"".equals(listbySql.get(0))) {
                                    if (listbySql.get(0) == 1) {
                                        //工程师PC端提交完工且需HD关单 发送邮件提醒
                                        this.sendEmailToHD(serviceId);
                                        systemService.updateBySqlString("update cbs_service set speed_status='7' where id='" + serviceId + "'");
                                    } else {
                                        systemService.updateBySqlString("update cbs_service set close_time ='" + s + "',status='4',speed_status='7' where id='" + serviceId + "'");
                                    }
                                } else {
                                    systemService.updateBySqlString("update cbs_service set close_time ='" + s + "',status='4',speed_status='7' where id='" + serviceId + "'");
                                }
                            }
                        }

                        //添加完工报告日志
                        TSUser tsUser = ResourceUtil.getSessionUserName();
                        CbsServiceEntity cbsServiceEntity = new CbsServiceEntity();
                        cbsServiceEntity.setId(serviceId);
                        if(editReport){
                            cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "补填了完工单。", null);
                        } else if (StringUtil.isNotEmpty(type) && type.equals("2")) {
                            cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "提交了完工报告并且关闭了服务单。", null);
                        } else {
                            cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "提交了完工报告。", null);
                        }
                    }
                    msg = cbsEngineSceneCheckReport.getStatus();
                } else {
                    flag = false;
                    msg = "服务单第三方已完工，请刷新服务单后再进行操作！";
                }
            }
        } catch (Exception e) {
            msg = "提交引擎翻新现场检测完工单异常";
            flag = false;
            e.printStackTrace();
            System.err.println("事务出现异常,回滚事务！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//此处采用手动回滚
        }
        j.setSuccess(flag);
        j.setMsg(msg);
        return j;
    }

    @Override
    public AjaxJson saveYqReport(HttpServletRequest request, CbsEngineAcceptEntity cbsEngineAccept) {
        AjaxJson j = new AjaxJson();
        String msg = "提交引擎翻新验收单成功！";
        boolean flag = true;
        String type = request.getParameter("type");
        //是否为 补填完工单
        Boolean editReport = Boolean.valueOf(oConvertUtils.getString(request.getParameter("editReport")));
        String[] finishFiles = request.getParameterValues("finishFiles");
        String[] photoFiles = request.getParameterValues("photoFiles");
        try {

            String serviceId = cbsEngineAccept.getServiceId();
            if (StringUtil.isNotEmpty(serviceId)) {
                //查询是否状态是否未完工
                List<Map<String, Object>> speedStatus = systemService.findForJdbc("select speed_status from cbs_service where id='" + serviceId + "'");
                //如果是补填完工单 或者 状态不是7
                if (editReport || (speedStatus.size() > 0 && !speedStatus.get(0).get("speed_status").toString().equals("7"))) {
                    /*暂存是0，提交是1，为了防止重复提交，先更新服务单状态*/
                    //如果不是补填完工单则更新服务单状态（防止影响原服务单状态）
                    if (!editReport && cbsEngineAccept.getStatus() == 1) {
                        systemService.updateBySqlString("update cbs_service set speed_status='" + StaticValue.fwywc + "' where id='" + serviceId + "'");
                    }
                    List<String> typeList = systemService.findListbySql("select type from zy_es_item where item='" + cbsEngineAccept.getEquipmentType() + "'");
                    if (typeList.size() != 0) {
                        ZyEquipmentTypeEntity zyEquipmentType = systemService.getEntity(ZyEquipmentTypeEntity.class, typeList.get(0));
                        cbsEngineAccept.setTypeId(zyEquipmentType);
                    }
                    cbsEngineAccept.setReportCategory("5");
                    if ("".equals(cbsEngineAccept.getId())) {
                        cbsEngineAccept.setId(null);
                    }
                    if (cbsEngineAccept.getId() != null && !"".equals(cbsEngineAccept.getId())) {
                        CbsEngineAcceptEntity t = systemService.get(CbsEngineAcceptEntity.class, cbsEngineAccept.getId());
                        MyBeanUtils.copyBeanNotNull2Bean(cbsEngineAccept, t);
                        systemService.saveOrUpdate(t);
                    } else {
                        systemService.saveOrUpdate(cbsEngineAccept);
                    }

                    //提交后对服务单的操作
                    if (cbsEngineAccept.getStatus() == 1) {
                        if(!editReport){
                            //判断服务单完工时，是否需要自动创建回访
                            cbsInspectionEvaluateService.assessService(serviceId);
                            List<CbsEngineAcceptEntity> hql = systemService.findHql("from CbsEngineAcceptEntity where service_id='" + serviceId + "'");
                            systemService.updateBySqlString("update cbs_service set report_type='7' ,report_id='" + hql.get(0).getId() + "' where id='" + serviceId + "'");
                            //关单时间
                            //获取系统当前时间
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String s = sdf.format(new Date());
                            List<Integer> listbySql = systemService.findListbySql("select hd_close from cbs_service where id='" + serviceId + "'");
                            if (StringUtil.isNotEmpty(type) && type.equals("2")) {
                                systemService.updateBySqlString("update cbs_service set close_time ='" + s + "',status='4',speed_status='7' where id='" + serviceId + "'");
                            } else {
                                if (listbySql.size() != 0 && listbySql.get(0) != null && !"".equals(listbySql.get(0))) {
                                    if (listbySql.get(0) == 1) {
                                        //工程师PC端提交完工且需HD关单 发送邮件提醒
                                        this.sendEmailToHD(serviceId);
                                        systemService.updateBySqlString("update cbs_service set speed_status='" + StaticValue.fwywc + "' where id='" + serviceId + "'");
                                    } else {
                                        systemService.updateBySqlString("update cbs_service set close_time ='" + s + "',status='" + StaticValue.ywc + "',speed_status='" + StaticValue.fwywc + "' where id='" + serviceId + "'");
                                    }
                                } else {
                                    systemService.updateBySqlString("update cbs_service set close_time ='" + s + "',status='" + StaticValue.ywc + "',speed_status='" + StaticValue.fwywc + "' where id='" + serviceId + "'");
                                }
                            }
                        }
                        //添加完工报告日志
                        TSUser tsUser = ResourceUtil.getSessionUserName();
                        CbsServiceEntity cbsServiceEntity = new CbsServiceEntity();
                        cbsServiceEntity.setId(serviceId);
                        if(editReport){
                            cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "补填了完工单。", null);
                        } else if (StringUtil.isNotEmpty(type) && type.equals("2")) {
                            cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "提交了完工报告,并且关闭了服务单。", null);
                        } else {
                            cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "提交了完工报告。", null);
                        }
                    }
                    msg = cbsEngineAccept.getStatus().toString();
                } else {
                    flag = false;
                    msg = "服务单第三方已完工，请刷新服务单后再进行操作！";
                }
            }
        } catch (Exception e) {
            msg = "添加引擎翻新验收单异常";
            flag = false;
            e.printStackTrace();
            System.err.println("事务出现异常,回滚事务！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//此处采用手动回滚
        }

        j.setSuccess(flag);
        j.setMsg(msg);
        return j;
    }

    @Override
    public AjaxJson zanAdd(CbsServiceReportEntity cbsServiceReport, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String message = "服务完工报告暂存成功";
        boolean flag = true;
        try {
            String reportId = request.getParameter("reportId");
            //获取新增备件信息
            String[] newEquipmentTypes = request.getParameterValues("newEquipmentType");
            String[] newEquipmentSns = request.getParameterValues("newEquipmentSn");
            String[] newEquipmentCodes = request.getParameterValues("newEquipmentCode");
            String[] newEquipments = request.getParameterValues("newEquipment");
            String[] oldEquipmentSns = request.getParameterValues("oldEquipmentSn");
            String[] oldEquipmentCodes = request.getParameterValues("oldEquipmentCode");
            CbsServiceEntity cbsServiceEntity = systemService.singleResult("from CbsServiceEntity where id = '" + cbsServiceReport.getServiceId().getId() + "'");

            if (StringUtil.isNotEmpty(cbsServiceEntity) && !cbsServiceEntity.getSpeedStatus().equals("7")) {
                if ("".equals(cbsServiceReport.getActualTime())) {
                    cbsServiceReport.setActualTime(null);
                }
                if ("".equals(cbsServiceReport.getFinishTime())) {
                    cbsServiceReport.setFinishTime(null);
                }
                if (reportId != null && !reportId.equals("")) {
                    CbsServiceReportEntity t = this.get(CbsServiceReportEntity.class, cbsServiceReport.getId());
                    MyBeanUtils.copyBeanNotNull2Bean(cbsServiceReport, t);
                    if ("".equals(t.getRepairAfterFile().getId())) {
                        t.setRepairAfterFile(null);
                    }
                    if ("".equals(t.getRepairFrontFile().getId())) {
                        t.setRepairFrontFile(null);
                    }
                    this.saveOrUpdate(t);
                } else {
                    if ("".equals(cbsServiceReport.getRepairAfterFile().getId())) {
                        cbsServiceReport.setRepairAfterFile(null);
                    }
                    if ("".equals(cbsServiceReport.getRepairFrontFile().getId())) {
                        cbsServiceReport.setRepairFrontFile(null);
                    }
                    cbsServiceReport.setStatus(0);
                    systemService.saveOrUpdate(cbsServiceReport);
                    systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
                }
                //  备件序列号更新
                if (newEquipmentTypes != null) {
                    List<CbsSceneEquipmentUseEntity> cbsSceneEquipmentUseEntityList = systemService.findHql("from CbsSceneEquipmentUseEntity where sceneReportId.id='" + cbsServiceReport.getId() + "'");
                    for (int i = 0; i < cbsSceneEquipmentUseEntityList.size(); i++) {
                        systemService.delete(cbsSceneEquipmentUseEntityList.get(i));
                    }
                    for (int i = 0; i < newEquipmentCodes.length; i++) {
                        //添加备件使用情况
                        CbsSceneEquipmentUseEntity cbsSceneEquipmentUseEntity = new CbsSceneEquipmentUseEntity();
                        CbsServiceReportEntity cbsServiceReportEntity = new CbsServiceReportEntity();
                        cbsServiceReportEntity.setId(cbsServiceReport.getId());
                        cbsSceneEquipmentUseEntity.setSceneReportId(cbsServiceReportEntity);
                        ZyEquipmentTypeEntity zyEquipmentTypeEntity = new ZyEquipmentTypeEntity();
                        zyEquipmentTypeEntity.setId(newEquipmentTypes[i]);
                        cbsSceneEquipmentUseEntity.setTypeId(zyEquipmentTypeEntity);
                        cbsSceneEquipmentUseEntity.setTypeDes(zyEquipmentTypeEntity);
                        cbsSceneEquipmentUseEntity.setSn(newEquipmentSns[i]);
                        cbsSceneEquipmentUseEntity.setEquipmentErcode(newEquipmentCodes[i]);
                        ZyEsItemEntity zyEsItemEntity = new ZyEsItemEntity();
                        zyEsItemEntity.setId(newEquipments[i]);
                        cbsSceneEquipmentUseEntity.setItemId(zyEsItemEntity);
                        cbsSceneEquipmentUseEntity.setOldErcode(oldEquipmentCodes[i]);
                        cbsSceneEquipmentUseEntity.setOldSn(oldEquipmentSns[i]);
                        systemService.save(cbsSceneEquipmentUseEntity);
                    }
                }
            } else {
                message = "服务完工报告第三方已完工，请刷新页面后操作！";
            }
        } catch (Exception e) {
            message = "服务完工报告暂存失败";
            flag = false;
            e.printStackTrace();
            System.err.println("事务出现异常,回滚事务！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//此处采用手动回滚
        }
        j.setMsg(message);
        j.setSuccess(flag);
        return j;

    }

    @Override
    public AjaxJson doAdd(CbsServiceReportEntity cbsServiceReport, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String message = "服务完工报告添加成功";
        boolean flag = true;
        try {
            //是否为补填完工单
            Boolean editReport = Boolean.valueOf(oConvertUtils.getString(request.getParameter("editReport")));
            String type = request.getParameter("type");
            String reportId = request.getParameter("reportId");
            String attr = request.getParameter("attr");
            //统计没有选择的附加任务
            String notChecked = request.getParameter("notChecked");
            //获取新增备件信息
            String[] newEquipmentTypes = request.getParameterValues("newEquipmentType");
            String[] newEquipmentSns = request.getParameterValues("newEquipmentSn");
            String[] newEquipmentCodes = request.getParameterValues("newEquipmentCode");
            String[] newEquipments = request.getParameterValues("newEquipment");
            String[] oldEquipmentSns = request.getParameterValues("oldEquipmentSn");
            String[] oldEquipmentCodes = request.getParameterValues("oldEquipmentCode");

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String closeTime = sdf.format(new Date());
            TSUser tsUser = ResourceUtil.getSessionUserName();
            CbsServiceEntity cbsServiceEntity = systemService.singleResult("from CbsServiceEntity where id = '" + cbsServiceReport.getServiceId().getId() + "'");
            if (editReport || StringUtil.isNotEmpty(cbsServiceEntity) && !cbsServiceEntity.getSpeedStatus().equals("7")) {
                if(!editReport){
                    systemService.updateBySqlString("update cbs_service set speed_status='" + StaticValue.fwywc + "' where id='" + cbsServiceEntity.getId() + "'");
                }

                if (reportId != null && !reportId.equals("")) {
                    CbsServiceReportEntity t = this.get(CbsServiceReportEntity.class, cbsServiceReport.getId());
                    MyBeanUtils.copyBeanNotNull2Bean(cbsServiceReport, t);
                    t.setStatus(1);

                    if ("".equals(t.getRepairAfterFile().getId())) {
                        t.setRepairAfterFile(null);
                    }
                    if ("".equals(t.getRepairFrontFile().getId())) {
                        t.setRepairFrontFile(null);
                    }
                    this.saveOrUpdate(t);
                    if(!editReport){//非 补填完工单操作时进行更新
                        systemService.updateBySqlString("update cbs_service set report_type= 1 ,report_id = '" + t.getId() + "' where id = '" + t.getServiceId().getId() + "'");
                    }
                    if(editReport){
                        cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "补填了完工单。", null);
                    } else if (t.getServiceId() != null) {
                        cbsServiceLogServiceI.addServiceLog(t.getServiceId(), StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "提交了完工报告。", null);
                    }
                    //TODO 判断服务单完工时，是否需要自动创建回访
                    cbsInspectionEvaluateService.assessService(t.getServiceId().getId());
                    //修改附加任务完成次数
                    if (attr != "" && attr != null) {
                        String[] split = attr.split(",");
                        if (split.length > 1) {
                            for (int i = 0; i < split.length; i++) {
                                systemService.updateBySqlString("UPDATE cbs_attach_task set complete_total = complete_total+1 where id = '" + split[i] + "'");
                                CbsServiceTaskMapEntity cbsServiceTaskMapEntity = new CbsServiceTaskMapEntity();
                                cbsServiceTaskMapEntity.setServiceId(t.getServiceId());
                                CbsAttachTaskEntity cbsAttachTaskEntity = systemService.singleResult("from CbsAttachTaskEntity where id = '" + split[i] + "'");
                                cbsServiceTaskMapEntity.setAttachTaskId(cbsAttachTaskEntity);
                                cbsServiceTaskMapEntity.setType("ywc");
                                systemService.saveOrUpdate(cbsServiceTaskMapEntity);
                            }
                        }
                        if (split.length == 1) {
                            systemService.updateBySqlString("UPDATE cbs_attach_task set complete_total = complete_total+1 where id = '" + split[0] + "'");
                            CbsServiceTaskMapEntity cbsServiceTaskMapEntity = new CbsServiceTaskMapEntity();
                            cbsServiceTaskMapEntity.setServiceId(t.getServiceId());
                            CbsAttachTaskEntity cbsAttachTaskEntity = systemService.singleResult("from CbsAttachTaskEntity where id = '" + split[0] + "'");
                            cbsServiceTaskMapEntity.setAttachTaskId(cbsAttachTaskEntity);
                            cbsServiceTaskMapEntity.setType("ywc");
                            systemService.saveOrUpdate(cbsServiceTaskMapEntity);
                        }
                    }
                    //修改附加任务未完成次数
                    if (notChecked != "" && notChecked != null) {
                        String[] split = notChecked.split(",");
                        if (split.length > 1) {
                            for (int i = 0; i < split.length; i++) {
                                systemService.updateBySqlString("UPDATE cbs_attach_task set not_complete_total = not_complete_total+1 where id = '" + split[i] + "'");
                                CbsServiceTaskMapEntity cbsServiceTaskMapEntity = new CbsServiceTaskMapEntity();
                                cbsServiceTaskMapEntity.setServiceId(t.getServiceId());
                                CbsAttachTaskEntity cbsAttachTaskEntity = systemService.singleResult("from CbsAttachTaskEntity where id = '" + split[i] + "'");
                                cbsServiceTaskMapEntity.setAttachTaskId(cbsAttachTaskEntity);
                                cbsServiceTaskMapEntity.setType("wwc");
                                systemService.saveOrUpdate(cbsServiceTaskMapEntity);
                            }
                        }
                        if (split.length == 1) {
                            systemService.updateBySqlString("UPDATE cbs_attach_task set not_complete_total = not_complete_total+1 where id = '" + split[0] + "'");
                            CbsServiceTaskMapEntity cbsServiceTaskMapEntity = new CbsServiceTaskMapEntity();
                            cbsServiceTaskMapEntity.setServiceId(t.getServiceId());
                            CbsAttachTaskEntity cbsAttachTaskEntity = systemService.singleResult("from CbsAttachTaskEntity where id = '" + split[0] + "'");
                            cbsServiceTaskMapEntity.setAttachTaskId(cbsAttachTaskEntity);
                            cbsServiceTaskMapEntity.setType("wwc");
                            systemService.saveOrUpdate(cbsServiceTaskMapEntity);
                        }
                    }
                } else {
                    if (cbsServiceReport.getRepairAfterFile().getId() == "") {
                        cbsServiceReport.setRepairAfterFile(null);
                    }
                    if (cbsServiceReport.getRepairFrontFile().getId() == "") {
                        cbsServiceReport.setRepairFrontFile(null);
                    }
                    cbsServiceReport.setStatus(1);
                    this.save(cbsServiceReport);
                    systemService.updateBySqlString("update cbs_service set report_type= 1 ,report_id = '" + cbsServiceReport.getId() + "' where id = '" + cbsServiceReport.getServiceId().getId() + "'");

                    //完工报告提交成功，添加日志
                    if (cbsServiceReport.getServiceId() != null) {
                        cbsServiceLogServiceI.addServiceLog(cbsServiceReport.getServiceId(), StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "提交了完工报告。", null);
                    }
                    //判断服务单完工时，是否需要自动创建回访
                    cbsInspectionEvaluateService.assessService(cbsServiceReport.getServiceId().getId());
                    //修改附加任务完成次数
                    if (attr != "" && attr != null) {
                        String[] split = attr.split(",");
                        if (split.length > 1) {
                            for (int i = 0; i < split.length; i++) {
                                systemService.updateBySqlString("UPDATE cbs_attach_task set complete_total = complete_total+1 where id = '" + split[i] + "'");
                                CbsServiceTaskMapEntity cbsServiceTaskMapEntity = new CbsServiceTaskMapEntity();
                                cbsServiceTaskMapEntity.setServiceId(cbsServiceReport.getServiceId());
                                CbsAttachTaskEntity cbsAttachTaskEntity = systemService.singleResult("from CbsAttachTaskEntity where id = '" + split[i] + "'");
                                cbsServiceTaskMapEntity.setAttachTaskId(cbsAttachTaskEntity);
                                cbsServiceTaskMapEntity.setType("ywc");

                                systemService.saveOrUpdate(cbsServiceTaskMapEntity);
                            }
                        }
                        if (split.length == 1) {
                            systemService.updateBySqlString("UPDATE cbs_attach_task set complete_total = complete_total+1 where id = '" + split[0] + "'");
                            //添加附加任务服务单表
                            CbsServiceTaskMapEntity cbsServiceTaskMapEntity = new CbsServiceTaskMapEntity();
                            cbsServiceTaskMapEntity.setServiceId(cbsServiceReport.getServiceId());
                            CbsAttachTaskEntity cbsAttachTaskEntity = systemService.singleResult("from CbsAttachTaskEntity where id = '" + split[0] + "'");
                            cbsServiceTaskMapEntity.setAttachTaskId(cbsAttachTaskEntity);
                            cbsServiceTaskMapEntity.setType("ywc");
                            systemService.saveOrUpdate(cbsServiceTaskMapEntity);
                        }
                    }
                    //修改附加任务未完成次数
                    if (notChecked != "" && notChecked != null) {
                        String[] split = notChecked.split(",");
                        if (split.length > 1) {
                            for (int i = 0; i < split.length; i++) {
                                systemService.updateBySqlString("UPDATE cbs_attach_task set not_complete_total = not_complete_total+1 where id = '" + split[i] + "'");
                                CbsServiceTaskMapEntity cbsServiceTaskMapEntity = new CbsServiceTaskMapEntity();
                                cbsServiceTaskMapEntity.setServiceId(cbsServiceReport.getServiceId());
                                CbsAttachTaskEntity cbsAttachTaskEntity = systemService.singleResult("from CbsAttachTaskEntity where id = '" + split[i] + "'");
                                cbsServiceTaskMapEntity.setAttachTaskId(cbsAttachTaskEntity);
                                cbsServiceTaskMapEntity.setType("wwc");
                                systemService.saveOrUpdate(cbsServiceTaskMapEntity);
                            }
                        }
                        if (split.length == 1) {
                            systemService.updateBySqlString("UPDATE cbs_attach_task set not_complete_total = not_complete_total+1 where id = '" + split[0] + "'");
                            CbsServiceTaskMapEntity cbsServiceTaskMapEntity = new CbsServiceTaskMapEntity();
                            cbsServiceTaskMapEntity.setServiceId(cbsServiceReport.getServiceId());
                            CbsAttachTaskEntity cbsAttachTaskEntity = systemService.singleResult("from CbsAttachTaskEntity where id = '" + split[0] + "'");
                            cbsServiceTaskMapEntity.setAttachTaskId(cbsAttachTaskEntity);
                            cbsServiceTaskMapEntity.setType("wwc");
                            systemService.saveOrUpdate(cbsServiceTaskMapEntity);
                        }
                    }
                }

                //不是 补填完工单时进行一下操作
                if(!editReport){
                    if (StringUtil.isNotEmpty(type) && type.equals("2")) {
                        systemService.updateBySqlString("update cbs_service set STATUS = '" + StaticValue.ywc + "',speed_status='" + StaticValue.fwywc + "',close_time='" + closeTime + "',close_user = '" + tsUser.getId() + "' where id = '" + cbsServiceReport.getServiceId().getId() + "'");
                        //维修服务单状态变为“已完成”，且报修人为微信用户时，通知微信用户评价服务单
                        if (cbsServiceEntity != null && cbsServiceEntity.getSourceType().equals("2")) {
                            if (cbsServiceEntity.getServiceType1() != null && cbsServiceEntity.getServiceType1().getName().equals("故障维修") && cbsServiceEntity.getServiceType1().getType() == 0) {
                                List<TSUser> wxUser = userService.getUserByMobilePhone(cbsServiceEntity.getContactsPhone());
                                if (StringUtil.isNotEmpty(wxUser) && wxUser.size() > 0) {
                                    if (StringUtil.isNotEmpty(wxUser) && wxUser.get(0).getOpenId() != null && !wxUser.get(0).getOpenId().equals("")) {
                                        /*发送微信提醒*/
                                        //调用微信接口发送
                                        List<Map<String, String>> list = new ArrayList<>();
                                        String msContent = "尊敬的客户：您的服务单<" + cbsServiceEntity.getCode() + ">的服务已经完成。请您在<个人中心>-<我的服务单>中对本次服务进行评价。【中影巴可客服部】";
                                        Map<String, String> map = new HashMap<>();
                                        map.put("openid", wxUser.get(0).getOpenId());
                                        map.put("message", msContent);
                                        list.add(map);
                                        wxCommonService.sendMsgForWx(list);
                                    }
                                }
                                //定时任务：维修服务单状态变为已完成，如果三日内用户没有评价自动好评
                                checkEvaluateStatus(cbsServiceEntity.getId());
                            }

                        }
                    } else {
                        if (cbsServiceEntity.getHdClose() != null) {
                            //不需要HD关单
//                  if (cbsServiceEntity!=null&&cbsServiceEntity.getHdClose()==0){
////                    systemService.updateBySqlString("update cbs_service set STATUS = '"+StaticValue.ywc+"',speed_status='"+ StaticValue.fwywc+"',close_time='"+closeTime+"' where id = '"+cbsServiceReport.getServiceId().getId()+"'");
////                }
                            //需要HD关单
                            if (cbsServiceEntity != null && cbsServiceEntity.getHdClose() == 1) {
                                systemService.updateBySqlString("update cbs_service set speed_status='" + StaticValue.fwywc + "',close_time='" + closeTime + "' where id = '" + cbsServiceReport.getServiceId().getId() + "'");
                                systemService.updateBySqlString("update cbs_service set close_time = NULL where id= '" + cbsServiceReport.getServiceId().getId() + "'");
                                this.sendEmailToHD(cbsServiceReport.getServiceId().getId());
                            } else {

                                systemService.updateBySqlString("update cbs_service set STATUS = '" + StaticValue.ywc + "',speed_status='" + StaticValue.fwywc + "',close_time='" + closeTime + "',close_user = '" + tsUser.getId() + "' where id = '" + cbsServiceReport.getServiceId().getId() + "'");
                                //维修服务单状态变为“已完成”，且报修人为微信用户时，通知微信用户评价服务单
                                if (cbsServiceEntity != null && cbsServiceEntity.getSourceType().equals("2")) {
                                    if (cbsServiceEntity.getServiceType1() != null && cbsServiceEntity.getServiceType1().getName().equals("故障维修") && cbsServiceEntity.getServiceType1().getType() == 0) {
                                        List<TSUser> wxUser = userService.getUserByMobilePhone(cbsServiceEntity.getContactsPhone());
                                        if (StringUtil.isNotEmpty(wxUser) && wxUser.size() > 0) {
                                            if (wxUser != null && wxUser.get(0).getOpenId() != null && !wxUser.get(0).getOpenId().equals("")) {
                                                /*发送微信提醒*/
                                                //调用微信接口发送
                                                List<Map<String, String>> list = new ArrayList<>();
                                                String msContent = "尊敬的客户：您的服务单<" + cbsServiceEntity.getCode() + ">的服务已经完成。请您在<个人中心>-<我的服务单>中对本次服务进行评价。【中影巴可客服部】";
                                                Map<String, String> map = new HashMap<>();
                                                map.put("openid", wxUser.get(0).getOpenId());
                                                map.put("message", msContent);
                                                list.add(map);
                                                wxCommonService.sendMsgForWx(list);
                                            }
                                        }
                                        //定时任务：维修服务单状态变为已完成，如果三日内用户没有评价自动好评
                                        checkEvaluateStatus(cbsServiceEntity.getId());
                                    }

                                }

                            }
                        } else {
                            systemService.updateBySqlString("update cbs_service set STATUS = '" + StaticValue.ywc + "',speed_status='" + StaticValue.fwywc + "',close_time='" + closeTime + "' where id = '" + cbsServiceReport.getServiceId().getId() + "'");
                            //维修服务单状态变为“已完成”，且报修人为微信用户时，通知微信用户评价服务单
                            if (cbsServiceEntity != null && cbsServiceEntity.getSourceType().equals("2")) {
                                if (cbsServiceEntity.getServiceType1() != null && cbsServiceEntity.getServiceType1().getName().equals("故障维修") && cbsServiceEntity.getServiceType1().getType() == 0) {
                                    List<TSUser> wxUser = systemService.findHql("from TSUser where mobilePhone='" + cbsServiceEntity.getContactsPhone() + "'");
                                    if (StringUtil.isNotEmpty(wxUser) && wxUser.size() > 0) {
                                        if (wxUser != null && wxUser.get(0).getOpenId() != null && !wxUser.get(0).getOpenId().equals("")) {
                                            /*发送微信提醒*/
                                            //调用微信接口发送
                                            List<Map<String, String>> list = new ArrayList<>();
                                            String msContent = "尊敬的客户：您的服务单<" + cbsServiceEntity.getCode() + ">的服务已经完成。请您在<个人中心>-<我的服务单>中对本次服务进行评价。【中影巴可客服部】";
                                            Map<String, String> map = new HashMap<>();
                                            map.put("openid", wxUser.get(0).getOpenId());
                                            map.put("message", msContent);
                                            list.add(map);
                                            wxCommonService.sendMsgForWx(list);
                                        }
                                    }
                                    //定时任务：维修服务单状态变为已完成，如果三日内用户没有评价自动好评
                                    checkEvaluateStatus(cbsServiceEntity.getId());

                                }

                            }
                        }
                    }
                }

//            备件序列号更新
                if (newEquipmentTypes != null) {
                    List<CbsSceneEquipmentUseEntity> cbsSceneEquipmentUseEntityList = systemService.findHql("from CbsSceneEquipmentUseEntity where sceneReportId.id='" + cbsServiceReport.getId() + "'");
                    for (int i = 0; i < cbsSceneEquipmentUseEntityList.size(); i++) {
                        systemService.delete(cbsSceneEquipmentUseEntityList.get(i));
                    }
                    for (int i = 0; i < newEquipmentCodes.length; i++) {
                        //添加备件使用情况
                    	String strOldsn = oldEquipmentSns[i].trim();
                        CbsSceneEquipmentUseEntity cbsSceneEquipmentUseEntity = new CbsSceneEquipmentUseEntity();
                        CbsServiceReportEntity cbsServiceReportEntity = new CbsServiceReportEntity();
                        cbsServiceReportEntity.setId(cbsServiceReport.getId());
                        cbsSceneEquipmentUseEntity.setSceneReportId(cbsServiceReportEntity);
                        ZyEquipmentTypeEntity zyEquipmentTypeEntity = new ZyEquipmentTypeEntity();
                        zyEquipmentTypeEntity.setId(newEquipmentTypes[i]);
                        cbsSceneEquipmentUseEntity.setTypeId(zyEquipmentTypeEntity);
                        cbsSceneEquipmentUseEntity.setTypeDes(zyEquipmentTypeEntity);
                        cbsSceneEquipmentUseEntity.setSn(newEquipmentSns[i]);
                        cbsSceneEquipmentUseEntity.setEquipmentErcode(newEquipmentCodes[i]);
                        ZyEsItemEntity zyEsItemEntity = new ZyEsItemEntity();
                        zyEsItemEntity.setId(newEquipments[i]);
                        cbsSceneEquipmentUseEntity.setItemId(zyEsItemEntity);
                        cbsSceneEquipmentUseEntity.setOldErcode(oldEquipmentCodes[i]);
                        cbsSceneEquipmentUseEntity.setOldSn(strOldsn);
                        systemService.save(cbsSceneEquipmentUseEntity);
                        //判断旧序列号是否属于服务单中的序列号
                        List<ZyEquipmentSpareEntity> zyEquipmentSpareEntityList = systemService.findHql("from ZyEquipmentSpareEntity where topItemSn = '" + cbsServiceEntity.getSn() + "'");
                        if (zyEquipmentSpareEntityList != null && zyEquipmentSpareEntityList.size() > 0) {
                        	int i1 = 0;
                            for (int m = 0; m < zyEquipmentSpareEntityList.size(); m++) {
                                if (zyEquipmentSpareEntityList.get(m).getSn().equals(strOldsn)) {
                                    String hql = "from ZyEquipmentSpareEntity where sn = '" + strOldsn + "'";
                                    ZyEquipmentSpareEntity zyEquipmentSpareEntity = systemService.singleResult(hql);
                                    ZyEsItemEntity zyEsItemEntity1 = systemService.singleResult("from ZyEsItemEntity where id = '" + newEquipments[i] + "'");
                                    i1 = systemService.updateBySqlString("update zy_equipment_spare set sn='" + newEquipmentSns[i] + "',item='" + zyEsItemEntity1.getItem() + "',type = '" + newEquipmentTypes[i] + "',qr_code = '" + newEquipmentCodes[i] + "' where id = '" + zyEquipmentSpareEntity.getId() + "'");
                                    //添加备件更换记录
                                    ZySpareRecordEntity zySpareRecordEntity = new ZySpareRecordEntity();
                                    zySpareRecordEntity.setEquipmentSn(cbsServiceEntity.getSn());
                                    zySpareRecordEntity.setOldSpareSn(strOldsn);
                                    /*新备件备件号*/
                                    if (StringUtil.isNotEmpty(newEquipments[i])) {
                                        ZyEsItemEntity zyEsItemEntity2 = systemService.get(ZyEsItemEntity.class, newEquipments[i].toString());
                                        zySpareRecordEntity.setNewSpareNo(zyEsItemEntity2.getItem());
                                    }
                                    if (StringUtil.isNotEmpty(cbsServiceEntity.getZyCinemaId())) {
                                        zySpareRecordEntity.setCinemaId(cbsServiceEntity.getZyCinemaId());
                                    }
                                    zySpareRecordEntity.setNewSpareSn(newEquipmentSns[i]);
                                    ZyEquipmentTypeEntity zeq = new ZyEquipmentTypeEntity();
                                    zeq.setId(newEquipmentTypes[i]);
                                    zySpareRecordEntity.setSpareDesc(zeq);
                                    zySpareRecordEntity.setReplaceReason("新旧备件替换");
                                    zySpareRecordEntity.setReplaceDate(new Date());
                                    zySpareRecordEntity.setCreateBy(tsUser.getUserName());
                                    zySpareRecordEntity.setCreateName(tsUser.getRealName());
                                    zySpareRecordEntity.setCreateDate(new Date());
                                    zySpareRecordEntity.setRelationServiceNo(cbsServiceEntity.getCode());
                                    systemService.save(zySpareRecordEntity);
                                }
                            }
                            //判断旧序列号是否无所属，且该设备无此类型备件
                            if (i1 <= 0) {
                            	ZyEquipmentSpareEntity zyEquipmentSpareEntity = systemService.singleResult("from ZyEquipmentSpareEntity where sn = '" + strOldsn + "'");
                            	if (zyEquipmentSpareEntity != null && !zyEquipmentSpareEntity.getTopItemSn().equals(cbsServiceEntity.getSn())) {
                            		//创建备件异常
                            		List<CbsEquipmentApplyEntity> hql = systemService.findHql("from CbsEquipmentApplyEntity where serviceId = '" + cbsServiceEntity.getId() + "' and status = 2 order by createDate desc");
                                    List<String> errorList = systemService.findListbySql("select id from cbs_equipment_error_log where is_close = 1 and sn='" + cbsServiceEntity.getSn() + "' and cbs_equipment_apply_id='" + hql.get(0).getId() + "'");
                                    if (errorList.size() == 0 || StringUtil.isEmpty(errorList.get(0))) {
                                		CbsEquipmentErrorLogEntity cbsEquipmentErrorLog = new CbsEquipmentErrorLogEntity();
	                                    cbsEquipmentErrorLog.setCbsEquipmentApplyId(hql.get(0).getId());
	                                    cbsEquipmentErrorLog.setSn(cbsServiceEntity.getSn());
	                                    cbsEquipmentErrorLog.setIsClose(1);
	                                    cbsEquipmentErrorLog.setAbnormalCause("备件序列号未通过验证");
	                                    systemService.save(cbsEquipmentErrorLog);
                                    }
                                    systemService.addLog("备件序列号更新异常", Globals.Log_Leavel_ERROR, Globals.Log_Type_OTHER);
                            	} else {
                            		// 比较同类型备件的序列号
                            		List<ZyEquipmentSpareEntity> typeEquipmentSpareEntityList = systemService.findHql("from ZyEquipmentSpareEntity where topItemSn = '" + cbsServiceEntity.getSn() + "' and type ='" + newEquipmentTypes[i] + "'");
                            		if (typeEquipmentSpareEntityList != null && typeEquipmentSpareEntityList.size() > 0) {
                            			//创建备件异常
	                                	List<CbsEquipmentApplyEntity> hql = systemService.findHql("from CbsEquipmentApplyEntity where serviceId = '" + cbsServiceEntity.getId() + "' and status = 2 order by createDate desc");
	                                    List<String> errorList = systemService.findListbySql("select id from cbs_equipment_error_log where is_close = 1 and sn='" + cbsServiceEntity.getSn() + "' and cbs_equipment_apply_id='" + hql.get(0).getId() + "'");
	                                    if (errorList.size() == 0 || StringUtil.isEmpty(errorList.get(0))) { 
		                                	CbsEquipmentErrorLogEntity cbsEquipmentErrorLog = new CbsEquipmentErrorLogEntity();
	                                        cbsEquipmentErrorLog.setCbsEquipmentApplyId(hql.get(0).getId());
	                                        cbsEquipmentErrorLog.setSn(cbsServiceEntity.getSn());
	                                        cbsEquipmentErrorLog.setIsClose(1);
	                                        cbsEquipmentErrorLog.setAbnormalCause("备件序列号未通过验证");
	                                        systemService.save(cbsEquipmentErrorLog);
                                        }
                                        systemService.addLog("备件序列号更新异常", Globals.Log_Leavel_ERROR, Globals.Log_Type_OTHER);
                            		} else {
                            			//添加备件更换记录
                                        ZySpareRecordEntity zySpareRecordEntity = new ZySpareRecordEntity();
                                        zySpareRecordEntity.setEquipmentSn(cbsServiceEntity.getSn());
                                        zySpareRecordEntity.setOldSpareSn(strOldsn);
                                        /*新备件备件号*/
                                        if (StringUtil.isNotEmpty(newEquipments[i])) {
                                            ZyEsItemEntity zyEsItemEntity2 = systemService.get(ZyEsItemEntity.class, newEquipments[i].toString());
                                            zySpareRecordEntity.setNewSpareNo(zyEsItemEntity2.getItem());
                                        }
                                        if (StringUtil.isNotEmpty(cbsServiceEntity.getZyCinemaId())) {
                                            zySpareRecordEntity.setCinemaId(cbsServiceEntity.getZyCinemaId());
                                        }
                                        zySpareRecordEntity.setNewSpareSn(newEquipmentSns[i]);
                                        ZyEquipmentTypeEntity zeq = new ZyEquipmentTypeEntity();
                                        zeq.setId(newEquipmentTypes[i]);
                                        zySpareRecordEntity.setSpareDesc(zeq);
                                        zySpareRecordEntity.setReplaceReason("新旧备件替换");
                                        zySpareRecordEntity.setReplaceDate(new Date());
                                        zySpareRecordEntity.setCreateBy(tsUser.getUserName());
                                        zySpareRecordEntity.setCreateName(tsUser.getRealName());
                                        zySpareRecordEntity.setCreateDate(new Date());
                                        zySpareRecordEntity.setRelationServiceNo(cbsServiceEntity.getCode());
                                        systemService.save(zySpareRecordEntity);
                                        
                                        //添加备件记录        			
                                        ZyEquipmentSpareEntity esSpare = new ZyEquipmentSpareEntity();
                            			esSpare.setSn(newEquipmentSns[i]);
                            			esSpare.setQrCode(newEquipmentCodes[i]);
                            			esSpare.setType(zeq);
                                        if (StringUtil.isNotEmpty(newEquipments[i])) {
                                            ZyEsItemEntity zyEsItemEntity2 = systemService.get(ZyEsItemEntity.class, newEquipments[i].toString());
                                            esSpare.setItem(zyEsItemEntity2.getItem());
                                        }
                            			esSpare.setTopItemSn(cbsServiceEntity.getSn());
                            			esSpare.setServerState(StaticValue.DIC_SERVER_STATE_1001);
                            			esSpare.setIsServicing("0");
                            			esSpare.setIsNormal("0");
                            			esSpare.setIsSpare(true);
                            			esSpare.setRepairDate(0);
                            			//20190619 add start 设置备件保期与设备一致 Amy 
                            			if (cbsServiceEntity.getZyEquipmentSpareId() != null ) {
                            				esSpare.setSendDate(cbsServiceEntity.getZyEquipmentSpareId().getSendDate());
                                			esSpare.setInstallDate(cbsServiceEntity.getZyEquipmentSpareId().getInstallDate());
                                			esSpare.setWarrantyBeginDate(cbsServiceEntity.getZyEquipmentSpareId().getWarrantyBeginDate());
                                			esSpare.setRepairEndDate(cbsServiceEntity.getZyEquipmentSpareId().getRepairEndDate());
                                			esSpare.setRepairDate(cbsServiceEntity.getZyEquipmentSpareId().getRepairDate());
                            			}                          			
                            			//20190619 add end 设置备件保期与设备一致 Amy
                            			systemService.save(esSpare);
                            		}
                            	}
                            }
                        } else {
                        	String hql1 = "from ZyEquipmentSpareEntity where sn = '" + cbsServiceEntity.getSn() + "'";
                        	//查询设备
	                          ZyEquipmentSpareEntity zyEquipmentSpareEntity1 = systemService.singleResult(hql1);
	                          if (zyEquipmentSpareEntity1 != null) {
	                        	//添加备件更换记录
                                  ZySpareRecordEntity zySpareRecordEntity = new ZySpareRecordEntity();
                                  zySpareRecordEntity.setEquipmentSn(cbsServiceEntity.getSn());
                                  zySpareRecordEntity.setOldSpareSn(strOldsn);
                                  /*新备件备件号*/
                                  if (StringUtil.isNotEmpty(newEquipments[i])) {
                                      ZyEsItemEntity zyEsItemEntity2 = systemService.get(ZyEsItemEntity.class, newEquipments[i].toString());
                                      zySpareRecordEntity.setNewSpareNo(zyEsItemEntity2.getItem());
                                  }
                                  if (StringUtil.isNotEmpty(cbsServiceEntity.getZyCinemaId())) {
                                      zySpareRecordEntity.setCinemaId(cbsServiceEntity.getZyCinemaId());
                                  }
                                  zySpareRecordEntity.setNewSpareSn(newEquipmentSns[i]);
                                  ZyEquipmentTypeEntity zeq = new ZyEquipmentTypeEntity();
                                  zeq.setId(newEquipmentTypes[i]);
                                  zySpareRecordEntity.setSpareDesc(zeq);
                                  zySpareRecordEntity.setReplaceReason("新旧备件替换");
                                  zySpareRecordEntity.setReplaceDate(new Date());
                                  zySpareRecordEntity.setCreateBy(tsUser.getUserName());
                                  zySpareRecordEntity.setCreateName(tsUser.getRealName());
                                  zySpareRecordEntity.setCreateDate(new Date());
                                  zySpareRecordEntity.setRelationServiceNo(cbsServiceEntity.getCode());
                                  systemService.save(zySpareRecordEntity);
                                  
                                  	//添加备件记录
                                  	ZyEquipmentSpareEntity esSpare = new ZyEquipmentSpareEntity();
	                      			esSpare.setSn(newEquipmentSns[i]);
	                      			esSpare.setQrCode(newEquipmentCodes[i]);
	                      			esSpare.setType(zeq);
	                                  if (StringUtil.isNotEmpty(newEquipments[i])) {
	                                      ZyEsItemEntity zyEsItemEntity2 = systemService.get(ZyEsItemEntity.class, newEquipments[i].toString());
	                                      esSpare.setItem(zyEsItemEntity2.getItem());
	                                  }
	                      			esSpare.setTopItemSn(cbsServiceEntity.getSn());
	                      			esSpare.setServerState(StaticValue.DIC_SERVER_STATE_1001);
	                      			esSpare.setIsServicing("0");
	                      			esSpare.setIsNormal("0");
	                      			esSpare.setIsSpare(true);
	                      			esSpare.setRepairDate(0);
	                      			//20190619 add start 设置备件保期与设备一致 Amy 
                        			esSpare.setSendDate(zyEquipmentSpareEntity1.getSendDate());
                            		esSpare.setInstallDate(zyEquipmentSpareEntity1.getInstallDate());
                            		esSpare.setWarrantyBeginDate(zyEquipmentSpareEntity1.getWarrantyBeginDate());
                            		esSpare.setRepairEndDate(zyEquipmentSpareEntity1.getRepairEndDate());
                            		esSpare.setRepairDate(zyEquipmentSpareEntity1.getRepairDate());                      			
                        			//20190619 add end 设置备件保期与设备一致 Amy
	                      			systemService.save(esSpare);
	                          } else {
                          		  CbsEquipmentErrorLogEntity cbsEquipmentErrorLog = new CbsEquipmentErrorLogEntity();
                          		  List<CbsEquipmentApplyEntity> hql = systemService.findHql("from CbsEquipmentApplyEntity where serviceId = '" + cbsServiceEntity.getId() + "' and status = 2 order by createDate desc");
                                  cbsEquipmentErrorLog.setCbsEquipmentApplyId(hql.get(0).getId());
                                  cbsEquipmentErrorLog.setSn(cbsServiceEntity.getSn());
                                  cbsEquipmentErrorLog.setIsClose(1);
                                  cbsEquipmentErrorLog.setAbnormalCause("备件序列号未通过验证");
                                  systemService.save(cbsEquipmentErrorLog);
	                        	  systemService.addLog("备件序列号更新异常", Globals.Log_Leavel_ERROR, Globals.Log_Type_OTHER);
	                          }
                        	}
                            systemService.addLog("备件序列号更新异常", Globals.Log_Leavel_ERROR, Globals.Log_Type_OTHER);
                        }
                    }
                
                systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
            } else {
                flag = false;
                message = "服务完工报告已完成，请刷新页面";
            }
        } catch (Exception e) {
            message = "服务完工报告添加失败";
            flag = false;
            e.printStackTrace();
            System.err.println("事务出现异常,回滚事务！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//此处采用手动回滚
        }
        j.setMsg(message);
        j.setSuccess(flag);
        return j;
    }

    @Override
    public AjaxJson addSceneCheckReport(HttpServletRequest request, CbsSceneCheckReportEntity cbsSceneCheckReport) {
        AjaxJson j = new AjaxJson();
        boolean flag = true;
        String message = "现场检测完工单提交成功";
        try {
            String type = request.getParameter("type");
            //是否为补填完工单
            Boolean editReport = Boolean.valueOf(oConvertUtils.getString(request.getParameter("editReport")));
            String orderTime = request.getParameter("orderTime");
            String[] finishFiles = request.getParameterValues("finishFiles");
            String[] repairFiles = request.getParameterValues("repairFiles");
            String[] rectificationFiles = request.getParameterValues("rectificationFiles");
            String[] photoFiles = request.getParameterValues("photoFiles");

            CbsServiceEntity cbsService = systemService.get(CbsServiceEntity.class, cbsSceneCheckReport.getServiceId());
            if (editReport || StringUtil.isNotEmpty(cbsService) && !cbsService.getSpeedStatus().equals("7")) {
                if (!editReport && "1".equals(cbsSceneCheckReport.getStatus())) {
                    systemService.updateBySqlString("update cbs_service set speed_status='" + StaticValue.fwywc + "' where id='" + cbsSceneCheckReport.getServiceId() + "'");
                }

                if (!editReport && StringUtil.isNotEmpty(orderTime)) {
                    systemService.updateBySqlString("update cbs_service set ORDER_TIME='" + orderTime + "' where id='" + cbsSceneCheckReport.getServiceId() + "'");
                }
                cbsSceneCheckReport.setReportCategory(3);
                if ("".equals(cbsSceneCheckReport.getId())) {
                    cbsSceneCheckReport.setId(null);
                }
                List<String> typeList = systemService.findListbySql("select type from zy_es_item where item='" + cbsSceneCheckReport.getEquipmentType() + "'");
                if (typeList.size() != 0) {
                    ZyEquipmentTypeEntity zyEquipmentType = systemService.getEntity(ZyEquipmentTypeEntity.class, typeList.get(0));
                    cbsSceneCheckReport.setTypeId(zyEquipmentType);
                }

                if (cbsSceneCheckReport.getId() != null && !"".equals(cbsSceneCheckReport.getId())) {
                    CbsSceneCheckReportEntity t = systemService.get(CbsSceneCheckReportEntity.class, cbsSceneCheckReport.getId());
                    MyBeanUtils.copyBeanNotNull2Bean(cbsSceneCheckReport, t);
                    systemService.saveOrUpdate(t);
                } else {
                    systemService.saveOrUpdate(cbsSceneCheckReport);
                }
                //提交后对服务单的操作
                if ("1".equals(cbsSceneCheckReport.getStatus())) {
                    if(!editReport){
                        //判断服务单完工时，是否需要自动创建回访
                        cbsInspectionEvaluateService.assessService(cbsSceneCheckReport.getServiceId());
                        List<CbsSceneCheckReportEntity> hql = systemService.findHql("from CbsSceneCheckReportEntity where service_id='" + cbsSceneCheckReport.getServiceId() + "'");
                        systemService.updateBySqlString("update cbs_service set report_type='4' ,report_id='" + hql.get(0).getId() + "' where id='" + cbsSceneCheckReport.getServiceId() + "'");
                        //关单时间
                        //获取系统当前时间
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String s = sdf.format(new Date());
                        List<Integer> listbySql = systemService.findListbySql("select hd_close from cbs_service where id='" + cbsSceneCheckReport.getServiceId() + "'");
                        if (StringUtil.isNotEmpty(type) && type.equals("2")) {
                            systemService.updateBySqlString("update cbs_service set close_time ='" + s + "',status='" + StaticValue.ywc + "',speed_status='7' where id='" + cbsSceneCheckReport.getServiceId() + "'");
                        } else {
                            if (listbySql.size() != 0 && listbySql.get(0) != null && !"".equals(listbySql.get(0))) {
                                if (listbySql.get(0) == 1) {
                                    //工程师PC端提交完工且需HD关单 发送邮件提醒
                                    this.sendEmailToHD(cbsSceneCheckReport.getServiceId());
                                    systemService.updateBySqlString("update cbs_service set speed_status='7' where id='" + cbsSceneCheckReport.getServiceId() + "'");
                                } else {
                                    systemService.updateBySqlString("update cbs_service set close_time ='" + s + "',status='" + StaticValue.ywc + "',speed_status='7' where id='" + cbsSceneCheckReport.getServiceId() + "'");
                                }
                            } else {
                                systemService.updateBySqlString("update cbs_service set close_time ='" + s + "',status='" + StaticValue.ywc + "',speed_status='7' where id='" + cbsSceneCheckReport.getServiceId() + "'");
                            }
                        }
                    }

                    //添加完工报告日志
                    TSUser tsUser = ResourceUtil.getSessionUserName();
                    if (StringUtil.isNotEmpty(cbsSceneCheckReport.getServiceId())) {
                        CbsServiceEntity cbsServiceEntity = new CbsServiceEntity();
                        cbsServiceEntity.setId(cbsSceneCheckReport.getServiceId());
                        if(editReport){
                            cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "补填了完工单。", null);
                        } else if (StringUtil.isNotEmpty(type) && type.equals("2")) {
                            cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "提交了完工报告并且关闭了服务单。", null);
                        } else {
                            cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "提交了完工报告。", null);
                        }
                    }
                }
                message = cbsSceneCheckReport.getStatus();
            } else {
                flag = false;
                message = "现场检测完工报告已完成，请刷新页面";
            }

        } catch (Exception e) {
            message = "现场检测完工报告添加失败";
            flag = false;
            e.printStackTrace();
            System.err.println("事务出现异常,回滚事务！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//此处采用手动回滚
        }
        j.setMsg(message);
        j.setSuccess(flag);
        return j;
    }

    //定时任务：维修服务单状态变为已完成，如果三日内用户没有评价自动好评
    public void checkEvaluateStatus(final String serviceId) {
        System.out.println("检查评价状态");
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                try {
                    List<CbsInspectionEvaluateEntity> evaluateEntity = systemService.findHql("from CbsInspectionEvaluateEntity where busType='type_2' and cbsService.id='" + serviceId + "'");
                    if (evaluateEntity != null && evaluateEntity.size() > 0) {
                        if (evaluateEntity.get(0) != null) {
                            if (StringUtil.isNotEmpty(evaluateEntity.get(0).getEvaluateState()) && evaluateEntity.get(0).getEvaluateState().equals("0")) {
                                wxCommonService.bestEvaluate(serviceId);
                                System.out.println("自动好评");
                            }
                        }
                    } else {
                        wxCommonService.bestEvaluate(serviceId);
                        System.out.println("自动好评");
                    }
                } catch (Exception e) {
                    System.err.println("自动评价失败");
                }

            }
        }, StaticValue.evaluateTime);
    }

    /**
     * 比较日期
     *
     * @param dt1
     * @param dt2
     * @return
     */
    public static int CompareDate(Date dt1, Date dt2) {
        try {
            if (dt1.getTime() > dt2.getTime()) {
                System.out.println("dt1 在dt2前");
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                System.out.println("dt1在dt2后");
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    //当前日期转化为MMdd字符转
    public String getDateStr(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("MMdd");
        String dateStr = df.format(date);
        return dateStr;
    }
}